import React, { useState, useEffect, useMemo } from 'react';
import { Button, message } from 'antd';
import PeriodList from './PeriodList';
import CommonModal from '@/components/CommonModal';
import CommonLoading from '@/components/CommonLoading';
import moment from 'moment';
import { handleExportExcel2 } from '@/utils/utils.jsx';
import { queryBillDetails } from '../../service';
import FormRender from '@/components/FormRender';
import { getFormItem } from './config';
import OperaBtnRender from '@/components/OperaBtnRender';
import '../../index.less';

const PeriodDetails = ({
  detailVisible,
  orderStatus,
  handleCancel,
  record,
  type,
}) => {
  //详情数据
  const [data, setData] = useState([]);
  // 搜索数据
  const [query, setQuery] = useState({
    timeType: '3'
  });
  //分页数据
  const [pagination, setPagination] = useState({
    current: 1,
    total: 0,
    pageSize: 20,
  });
  const [loading, setLoading] = useState(false);

  //取消
  const onCancel = () => {
    handleCancel();
  };

  // 列表数据
  const periodListProps = {
    data,
    type,
    orderStatus,
    handleCancel,
    pagination,
    changePages(current, pageSize) {
      setPagination({
        ...pagination,
        current,
        pageSize,
      });
      getAccountDetail(query, { ...pagination, current, pageSize });
    },
  };

  useEffect(() => {
    if (detailVisible) {
      getAccountDetail(query, pagination);
    }
  }, [detailVisible]);

  // 获取账期明细
  const getAccountDetail = async (query, pagination) => {
    setLoading(true);
    setData([]);
    const { success, data = {} } = await queryBillDetails({
      ...query,
      current: pagination.current,
      size: pagination.pageSize,
      contractNo: record.contractNo,
      transType: Number(query.transType),
      period: type != '2' ? record.period : undefined,
      creditOrderState: orderStatus ? orderStatus : undefined,
      billingStatus: type == '1' ? '1,2' : type == '3' ? '3' : undefined,
      startTime: query.payTime
        ? moment(query.payTime[0]).format('YYYY-MM-DD HH:mm:ss')
        : undefined,
      endTime: query.payTime
        ? moment(query.payTime[1]).format('YYYY-MM-DD HH:mm:ss')
        : undefined,
      payTime: undefined,
    });
    if (success) {
      const { records = [], total = 0 } = data;
      setData(records);
      setPagination({
        ...pagination,
        total,
      });
    }
    setLoading(false);
  };

  const formArr = useMemo(() => {
    return getFormItem(type);
  }, [type])

  // 搜索组件数据
  const formRenderProps = {
    query,
    formArr,
    formConfig: {
      name: 'period-detail-search',
      style: { padding: '0px 0px 16px' }
    },
    clickSearch (val) {
      setQuery({ ...val });
      setData([]);
      setPagination({ ...pagination, current: 1 });
      getAccountDetail({ ...val }, { ...pagination, current: 1 });
    },
    clickReset () {
      setData([]);
      setQuery({ timeType: '3' });
      setPagination({ ...pagination, current: 1 });
      getAccountDetail(
        {},
        {
          ...pagination,
          current: 1,
        }
      );
    }
  }

  // 搜索组件数据
  // const SearchProps = {
  //   type,
  //   query,
  //   // 点击搜索事件
  //   handleSearch(val) {
  //     setQuery({ ...val });
  //     setData([]);
  //     setPagination({ ...pagination, current: 1 });
  //     getAccountDetail({ ...val }, { ...pagination, current: 1 });
  //   },
  //   // 重置
  //   handleReset() {
  //     setData([]);
  //     setQuery({});
  //     setPagination({ ...pagination, current: 1 });
  //     getAccountDetail(
  //       {},
  //       {
  //         ...pagination,
  //         current: 1,
  //       }
  //     );
  //   },
  // };

  // 分页组件数据
  // const PageProps = {
  //   pagination,
  //   handleChange(current, pageSize) {
  //     setPagination({
  //       ...pagination,
  //       current,
  //       pageSize,
  //     });
  //     getAccountDetail(query, { ...pagination, current, pageSize });
  //   },
  // };

  //表格导出
  const exportExcel = () => {
    if (data.length) {
      if (data.length > 10000) {
        message.info('导出数据超出1万条，请重新选择时间范围');
      } else {
        setLoading(true);
        const params = {
          ...query,
          contractNo: record.contractNo,
          period: type != '2' ? record.period : undefined,
          creditOrderState: orderStatus ? orderStatus : undefined,
          billingStatus: type == '1' ? '1,2' : type == '3' ? '3' : undefined,
          startTime: query.payTime
            ? moment(query.payTime[0]).format('YYYY-MM-DD HH:mm:ss')
            : undefined,
          endTime: query.payTime
            ? moment(query.payTime[1]).format('YYYY-MM-DD HH:mm:ss')
            : undefined,
          payTime: undefined,
        };
        let url = `/blade-user/ReceptionCredit/billOutDetailIncountExcel`,
          title = '待还明细.xlsx';
        if (type == '2') {
          (url = `/blade-user/ReceptionCredit/DetailNotIncountExcel`),
            (title = '未入账明细.xlsx');
        } else if (type == '3') {
          title = '历史账期明细.xlsx';
        }
        handleExportExcel2(url, params, title, () => {
          setLoading(false);
        });
      }
    } else {
      message.info('暂无可导出的数据');
    }
  };

  //操作按钮
  const btnArr = [
    { elType: 'button', text: '表格导出', onClick: exportExcel }
  ]

  return (
    <CommonModal
      title="账单明细"
      visible={detailVisible}
      footer={[
        <Button key="cancel" onClick={onCancel}>
          关闭
        </Button>,
      ]}
      onCancel={onCancel}
      width={1200}
    >
      <div>
        <FormRender { ...formRenderProps } />
        <OperaBtnRender style={{ marginBottom: '12px' }} btnArr={btnArr} />
        <div className="store-text" style={{ marginBottom: '10px' }}>
          供应商：{record?.storeName}
        </div>
        <PeriodList {...periodListProps} />
        <CommonLoading loading={loading} />
      </div>
    </CommonModal>
  );
};

export default React.memo(PeriodDetails, (prev, next) => {
  if (prev.detailVisible !== next.detailVisible) {
    return false;
  }
  return true;
});
